#!/usr/bin/perl -w

use strict;

my %vars = ();
my $result = '';

while (<>)
{
    s/\b([nps](?:_\d+)*)\b/$1_v/g;
    s/\b([nps])(\d)((?:_\d+)*)\b/$1$3_v$2/g;

    if (my @vars = /\b([nps][0-9_]*_v)[01]?\b/g)
    {
        for my $var (@vars)
        {
            $vars{$var} = 1;
        }
    }
    $result .= $_;
}

sub valv {
    my ($v) = @_;
    my @ordering = (qr/^n/, qr/^p/, qr/^s/);

    for (my $i = 0; $i <= $#ordering; ++$i)
    {
        return $i if $v =~ $ordering[$i];
    }

    die "unexpected variable: $v";
}

sub cmpv {
    my ($va,$vb) = (valv($a), valv($b));
    if ($va == $vb)
    {
        return $a cmp $b;
    }
    else
    {
        return $va <=> $vb;
    }
}

my @vars = keys %vars;
my $vars = join(' ', sort cmpv @vars);
$result =~ s/VARS/$vars/;

print $result;
